from app import db

class BaseModel(db.Model):
    __abstract__ = True #当前类只是被继承，不会直接执行
    id = db.Column(db.Integer,primary_key = True,autoincrement = True)

    def save(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def update(self):
        db.session.commit()

class Position(BaseModel):
    __tablename__ = "position" #定义表名，默认表名是类名的小写
    p_name = db.Column(db.String(32))
    pos_person = db.relationship(
        "Person",
        backref = "person_position"
    ) #反向映射

class Person(BaseModel):
    __tablename__ = "person"
    per_name = db.Column(db.String(32))
    position_id = db.Column(db.Integer,db.ForeignKey("position.id")) #外键

db.create_all()


#插入人
per = Person()
per.per_name = "马老二"
per.save()

#将已有员工，晋升为经理，使用反向映射
pos = Position()
pos.p_name = "经理"
pos.pos_person.append(per)
pos.save()

# #插入职位
pos = Position()
pos.p_name = "经理"
pos.save()

# 招聘牛老五为经理，使用反向映射
per = Person()
per.per_name = "牛老五"
per.person_position = pos #插入的是职位的对象
per.save()

# #插入职位
pos = Position()
pos.p_name = "董事长"
pos.save()

#插入人，不使用反向映射
per = Person()
per.per_name = "金百万"
per.position_id = 1 #插入的是职位的id
per.save()

#查金万两的职位
per = Person.query.get(1)
print(per.per_name)
print(per.position_id)
print(per.person_position.p_name)

# #查董事长的人
pos = Position.query.get(1)
print(pos.p_name)
print(pos.pos_person)
print([i.per_name for i in pos.pos_person])